#include "render_label.h"
#include "qbe/src/layout/layout.hpp"
#include "qlib/utils/font.h"

namespace qbe::utils::TempRender {

RenderLabel::RenderLabel(vsg::ref_ptr<vsg::Options> options, std::vector<qlib::Label::s_ptr> labels) : m_labels(labels) {
  switchObject = vsg::Switch::create();
  transform = vsg::MatrixTransform::create();
  switchObject->addChild(true, transform);

  std::vector<Mesh2D> meshs;
  for (auto i : m_labels) {
    auto lines = qlib::get_text(i->text, i->origin, i->fontSize, i->rotation, i->anchor);
    auto mesh = Mesh2D();
    auto vertices = vsg::vec2Array::create(lines.size());
    auto indices = vsg::uintArray::create(lines.size());
    for (uint32_t i = 0; i < lines.size(); i++) {
      (*vertices)[i] = {float(lines[i].x), float(lines[i].y)};
      (*indices)[i] = i;
    }
    mesh.vertices = vertices;
    mesh.indices = indices;
    meshs.push_back(mesh);
    meshs.push_back(mesh);
  }
  Mesh2D merge_result;
  mesh_merge(meshs, merge_result);
  LineShaderMaterial2D material{Line_Uniform{vsg::vec4(1.0, 0.0, 0.0, 1.0), vsg::vec2(1316.0, 847.0), 100.0, 70.0, true},
                                "shaders/cell/line.vert.spv", "shaders/cell/line.frag.spv"};

  line_node = LineMeshNode::create(options, qlib::Tag{0, 0}, merge_result, material, VkPrimitiveTopology::VK_PRIMITIVE_TOPOLOGY_LINE_LIST);
  transform->addChild(line_node);
}

RenderLabel ::~RenderLabel() {}

void RenderLabel::setLayerType(vsg::vec4 color, std::string line_type) {
  line_node->setLayerType(color, line_type);
}

void RenderLabel::updateData(std::vector<qlib::Label::s_ptr> labels) {
  if (labels.empty())
    return;
  m_labels = labels;
  std::vector<Mesh2D> meshs;
  for (auto i : m_labels) {
    auto lines = qlib::get_text(i->text, i->origin, i->fontSize, i->rotation, i->anchor);
    auto mesh = Mesh2D();
    auto vertices = vsg::vec2Array::create(lines.size());
    auto indices = vsg::uintArray::create(lines.size());
    for (uint32_t i = 0; i < lines.size(); i++) {
      (*vertices)[i] = {float(lines[i].x), float(lines[i].y)};
      (*indices)[i] = i;
    }
    mesh.vertices = vertices;
    mesh.indices = indices;
    meshs.push_back(mesh);
    meshs.push_back(mesh);
  }
  Mesh2D merge_result;
  mesh_merge(meshs, merge_result);
  line_node->mesh = merge_result;
  line_node->update();
}

void RenderLabel::setShowHide(bool is_show) {
  switchObject->setAllChildren(is_show);
}

}  // namespace qbe::utils::TempRender